package com.gm.wholesale.module.main.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.gm.commonlib.base.baseBean.DataResp
import com.gm.commonlib.base.baseui.baseactivity.BaseActivity
import com.gm.commonlib.module.evenbus.EventMessage
import com.gm.commonlib.network.BaseHttpObserver
import com.gm.commonlib.util.permission.PermissionUtil
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback
import com.gm.commonlib.views.dialog.DialogUtil
import com.gm.commonlib.views.popupwindow.Popupwindow
import com.gm.commonlib.views.toast.ToastUtil
import com.gm.wholesale.GMApplication
import com.gm.wholesale.R
import com.gm.wholesale.bluetooth.BluetoothUtil
import com.gm.wholesale.bluetooth.DeviceManger
import com.gm.wholesale.bluetooth.bean.DeviceBean
import com.gm.wholesale.bluetooth.bean.WeightBean
import com.gm.wholesale.bluetooth.interfaces.OnConnectionBluListener
import com.gm.wholesale.bluetooth.weightBlue.WeightBlueManger
import com.gm.wholesale.cacheData.PatchCache
import com.gm.wholesale.constant.Constant
import com.gm.wholesale.constant.MenuData
import com.gm.wholesale.databinding.ActivityMainBinding
import com.gm.wholesale.module.appUpdate.UpdateAppUtil
import com.gm.wholesale.module.config.ConfigData
import com.gm.wholesale.module.custom.ChoiceCustomData
import com.gm.wholesale.module.custom.bean.CustomBean
import com.gm.wholesale.module.custom.bean.DefaultCustomBean
import com.gm.wholesale.module.custom.model.CustomModel
import com.gm.wholesale.module.custom.view.CustomView
import com.gm.wholesale.module.evenbus.EvenBusUtil
import com.gm.wholesale.module.evenbus.EventBusType
import com.gm.wholesale.module.good.bean.GoodBean
import com.gm.wholesale.module.good.bean.GoodListBean
import com.gm.wholesale.module.main.listener.MyDrawerLayoutListener
import com.gm.wholesale.module.main.presenter.CreateOrderUiPre
import com.gm.wholesale.module.main.presenter.MainPresenter
import com.gm.wholesale.module.main.presenter.VoiceViewPresenter
import com.gm.wholesale.module.order.bean.OrderDetailBean
import com.gm.wholesale.module.order.ui.MainOrderFragment
import com.gm.wholesale.module.voice.voiceCreateOrder.VoiceCreateOrderManger
import com.gm.wholesale.util.AppUtil
import com.gm.wholesale.util.ViewUtil
import com.gm.wholesale.view.HeaderView
import com.j256.ormlite.stmt.query.In
import com.taobao.sophix.SophixManager
import kotlin.system.exitProcess

class MainActivity : BaseActivity() {
    private var mExitTime: Long = 0
    private var mHeaderView: HeaderView? = null //title
    private var mDrawerLayout: DrawerLayout? = null //侧滑控件
    private var mLeftMenuFragment: LeftMenuFragment? = null //侧滑菜单
    var mCreateOrderUiPre: CreateOrderUiPre? = null //创建单子界面
    private var mVoiceViewPresenter: VoiceViewPresenter? = null
    private var mMainOrderFragment: MainOrderFragment? = null
    var mIsConnection = false
    private var mCustomView: CustomView? = null
    val gMApplication: GMApplication
        get() = baseApplication as GMApplication
    var mIsNeedNt = false
    private var sConfigData: ConfigData? = null
    private var mCurrentMenuData: MenuData? = null
    private var mainPresenter: MainPresenter? = null
    private var mListener: ConnectionListener? = null
    private var mWeightBlueManger: WeightBlueManger? = null
    private var mainView: ActivityMainBinding? = null;

    companion object {
        var mActivity: MainActivity? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        PatchCache.clearnOldCacheData()
        loadNewPatch()
        registerReStartApp()
        mListener = ConnectionListener()
        sConfigData = ConfigData.getConfigData()
        mActivity = this
        setContentView(R.layout.activity_main)
        initView()
        initPresenter()
        handelViewByPermission()
    }

    //todo 加载阿里后台发布的补丁包
    private fun loadNewPatch() {
        SophixManager.getInstance().queryAndLoadNewPatch()
    }

    //todo 注册广播监听补丁瞎子啊完成，用户点击重启关闭app
    private fun registerReStartApp() {
        val intentFilter = IntentFilter()
        intentFilter.addAction(Constant.reStartApp)
        registerReceiver(ReStartApp(), intentFilter)
    }

    internal inner class ReStartApp : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            DialogUtil.show(activity, "补丁下载成功，请重启应用") { _, _ ->
                finish()
                AppUtil.exitApp()
                exitProcess(0)
            }
        }
    }

    //todo 更具权限不同，显示不同得界面
    private fun handelViewByPermission() {
        if (sConfigData == null) { //todo 按道理不可能走这里，防止空指针做个处理
            mainPresenter!!.showOrderMangerUI()
            mHeaderView!!.hidBackView()
            return
        }
        if (!sConfigData!!.hasCreateOrderPermission()) { //没有开单权限，进入订单管理界面
            mainPresenter!!.showOrderMangerUI()
            mHeaderView!!.hidBackView()
        } else {
            mWeightBlueManger = WeightBlueManger.newInstance()
            mWeightBlueManger?.initWeightBlue(activity)
            startConnectionBlue()
            getDefaultCustom();
            //语音录单权限
            if (sConfigData!!.hasVoicePermission()) {
                //  VoiceManger.getVoiceManger().init(this);
            }
        }
    }

    override fun onResume() {
        UpdateAppUtil.getAppVersion(this)
        super.onResume()
    }

    internal inner class ConnectionListener : OnConnectionBluListener {
        override fun connection(deviceBean: DeviceBean) {
            mIsNeedNt = false
            mIsConnection = true
            ToastUtil.showToast("连接蓝牙秤成功")
            if (deviceBean != null) {
                DeviceManger.getDeviceManger().saveWeightDevice(deviceBean)
            }
            EvenBusUtil.connectionSuccess()
            hidLoadingDialog()
        }

        override fun connectionFail() {
            if (isFinishing) {
                return
            }
            if (mWeightBlueManger != null) {
                mWeightBlueManger!!.setFailState()
            }
            if (mIsNeedNt) {
                DialogUtil.showConnectionWeightFail(getContext())
                mIsNeedNt = false
            }
            hidLoadingDialog()
            mIsConnection = false
            DeviceManger.getDeviceManger().cleanWeightDevice()
            EvenBusUtil.connectionFail()
        }

        override fun getNumber(weightBean: WeightBean) {
            if (mCreateOrderUiPre != null) {
                mCreateOrderUiPre!!.setNumBer(weightBean)
            }
            VoiceCreateOrderManger.newInstance().setWeightBean(weightBean)
        }
    }

    private fun startConnectionBlue() {
        mIsNeedNt = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PermissionUtil.aplyBluePermission(this, object : IPermissionCallback() {
                override fun onPermissionResult(result: Boolean, dataSet: Set<String>) {
                    if (result && mWeightBlueManger != null) {
                        mWeightBlueManger!!.connectionWeightBlue(activity, mListener)
                    } else {
                        BluetoothUtil.showNotPermiss()
                        ViewUtil.showPrintError()
                    }
                }
            })
        } else {
            PermissionUtil.aplyLocationPermission(this, object : IPermissionCallback() {
                override fun onPermissionResult(result: Boolean, dataSet: Set<String>) {
                    if (mWeightBlueManger != null) {
                        mWeightBlueManger!!.connectionWeightBlue(activity, mListener)
                    }
                }
            })
        }
    }

    //todo 初始创建订单控制器
    private fun initPresenter() {
        mainPresenter = MainPresenter(this, mMainOrderFragment!!)
        mCreateOrderUiPre = CreateOrderUiPre(
            this, mMainOrderFragment
        )
    }

    //todo 获取默认散户数据
     fun getDefaultCustom() {
        CustomModel.getDefaultCustom(
            null,
            object : BaseHttpObserver<DataResp<DefaultCustomBean?>?>() {
                override fun handleResultOkResp(resp: DataResp<DefaultCustomBean?>?) {
                    val defaultCustomBean = resp?.data
                    if (defaultCustomBean != null) {
                        val customBean = CustomBean()
                        customBean.name = defaultCustomBean.name
                        customBean.id = defaultCustomBean.id
                        ChoiceCustomData.newInstance().customBean = customBean
                        ChoiceCustomData.newInstance().setSanKeCustomBean(customBean)
                        EvenBusUtil.updateHomeDefaultCustorm(customBean)
                    }
                }
            }.setAutoErrorToast(false)
        )
    }

    // todo 弹出先择客户的界面
    fun showChoiceCustom() {
        if (mCustomView == null) {
            mCustomView = CustomView(mActivity)
        } else {
            mCustomView!!.updateView()
        }
        mCustomView!!.setCustomChoiceListener { customBean: CustomBean? ->
            EvenBusUtil.updateHomeDefaultCustorm(
                customBean
            )
        }
        Popupwindow.showPopCenterView(mActivity, mCustomView)
    }

    // todo 创建订单界面，输入数量单价
    fun showCreateOrderView(goodBean: GoodBean?) {
        if (mCreateOrderUiPre == null) return
        mCreateOrderUiPre!!.showCreateOrderView(goodBean)
    }

    //显示语音输入view
    fun startVoice() {
        if (mVoiceViewPresenter == null) {
            mVoiceViewPresenter = VoiceViewPresenter()
        }
        mVoiceViewPresenter!!.showView(this)
    }

    //todo 语音录单修改商品
    fun updateGoodForVoiceView(goodBean: GoodBean?) {
        mCreateOrderUiPre!!.updateGoodForVoice(goodBean)
    }

    fun initView() {
        mHeaderView = findViewById(R.id.headerView)
        mDrawerLayout = findViewById(R.id.drawerLayout)
        mLeftMenuFragment =
            supportFragmentManager.findFragmentById(R.id.leftMenuView) as LeftMenuFragment?
        mDrawerLayout?.setScrimColor(getColorById(R.color.color_transp80))
        mMainOrderFragment =
            supportFragmentManager.findFragmentById(R.id.orderFragment) as MainOrderFragment?
        setLeftMenuItemClickListener()
        mHeaderView?.setOnLogoClickListener { _: View? ->
            mDrawerLayout?.openDrawer(
                GravityCompat.START
            )
        }
        mHeaderView?.setOnBackClickListener { _: View? ->
            mHeaderView?.hidBackView()
            mainPresenter!!.showMainUI()
        }
        //todo 左边关闭后，在执行其他操作，不然可能感觉卡顿
        mDrawerLayout?.addDrawerListener(object : MyDrawerLayoutListener() {
            override fun onDrawerClosed(drawerView: View) {
                showFunctionUI()
            }
        })
    }

    private fun showFunctionUI() {
        if (mCurrentMenuData == null) return
        // todo 有开单权限才显示 返回开单按钮
        if (sConfigData!!.hasCreateOrderPermission()) {
            //显示返回按钮
            mHeaderView!!.showBackView()
        }
        //订单管理
        mainPresenter!!.showFunctionUI(mCurrentMenuData!!, mHeaderView)
        mCurrentMenuData = null
    }

    private fun setLeftMenuItemClickListener() {

        mLeftMenuFragment!!.setonMenuItemClickListener(object :
            LeftMenuFragment.OnMenuItemClickListener {
            override fun onMenuItemClickListener(menuData: MenuData?) {
                mCurrentMenuData = menuData
                //隐藏侧滑菜单
                mDrawerLayout!!.closeDrawer(Gravity.LEFT)
            }

        });

    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exit() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            ToastUtil.showToast("再按一次退出")
            mExitTime = System.currentTimeMillis()
        } else {
            AppUtil.exitApp()
            finish()
            exitProcess(0)
        }
    }

    override fun onDestroy() {
        DeviceManger.onDestroy(null)
        super.onDestroy()
    }

    fun startConnection() {
        if (!mWeightBlueManger!!.isConnection) {
            mIsNeedNt = true
            startConnectionBlue()
        }
    }

    //网页那边更新数据，这边同步更新
    fun updateCustom(type: Int, customBean: CustomBean) {
        val choiceCustomBean = ChoiceCustomData.newInstance().customBean ?: return
        //todo 修改的客户和我们主界面使用的客户是一个，需要更新主界面。
        if (choiceCustomBean.id == customBean.id) {
            if (type == 1) { //该客户被删除了，使用默认散客数据
                getDefaultCustom()
            } else if (type == 2) { //修改操作
                updateCustom(customBean)
                ChoiceCustomData.newInstance().customBean = customBean
            }
        }

    }

    //更新客户信息
    fun updateCustom(customBean: CustomBean?) {
        EvenBusUtil.updateHomeDefaultCustorm(customBean)
    }

    fun showMainUI() {
        mainPresenter!!.showMainUI()
        mHeaderView!!.hidBackView()
    }

    override fun onReceiveEvent(event: EventMessage<*>) {
        super.onReceiveEvent(event)
        if (event.code == EventBusType.CONNECTION_DEVICE.type) {
            val deviceBean = event.data as DeviceBean
            if (deviceBean != null) {
                if (mWeightBlueManger != null) {
                    mWeightBlueManger!!.connection(deviceBean, activity, mListener)
                }
            }
        } else if (event.code == EventBusType.TO_AFTERSALEVIEW.type) {
            val orderDetailBean = event.data as OrderDetailBean
            mainPresenter!!.showAftersaleFragment(orderDetailBean)
        } else if (event.code == EventBusType.CREATE_GOOD.type) {
            mainPresenter!!.showCreateGoodUI(event.data as GoodListBean)
        } else if (event.code == EventBusType.CREATE_CUSTORM.type) {
            mainPresenter!!.showCreateCustormUI(event.data as CustomBean)
        }
    }


    // todo 语音开单 直接创建订单（有重量直接创建）
    fun createOrder(goodBean: GoodBean?) {
        mCreateOrderUiPre?.createOrder(goodBean);
    }

    // todo 语音开单 跳转到创建订单界面
    fun showCreateOrderViewByVoice(goodName: String) {
        mCreateOrderUiPre?.showCreateOrderViewByVoice(goodName);
    }
}